<!--
 * @Description: 奈雪的茶多选
 * @Author: Kerwin
 * @Date: 2025-05-08 16:19:21
 * @LastEditTime: 2025-06-15 16:38:13
 * @LastEditors:  Please set LastEditors
-->
<template>
    <view class="goodsChoose">
        <!-- 选购类 -->
        <view class="optionalBox" v-if="goodsItem.spu_specs">
            <view class="optionalItem" v-for="(item, index) in goodsItem.spu_specs" :key="item.id">
                <view class="goodsName">{{ item.name }}</view>

                <view class="goodsItem">
                    <view class="optional" :class="{
                        activeOptional: goods.checked,
                        hiddenBorder: hiddenIds.includes(goods.name) && !isDisabled(item, goods),
                        disabled: isDisabled(item, goods)
                    }" @click="handleOptionalClick(item, goods,)" v-for="(goods, index) in item.values"
                        :key="goods.id">
                        <view class="name"
                            :class="{ hidden: hiddenIds.includes(goods.id) && !isDisabled(item, goods) }">
                            {{ goods.name }} <text v-if="goods.price != 0 && goods.price">|</text> <text
                                class="goods-price" v-if="goods.price != 0 && goods.price">￥{{ goods.price }}</text>
                        </view>

                        <!-- 售罄蒙版 -->
                        <view class="mode" v-if="goods.enable === false">
                            <view class="mode-text">售罄</view>
                        </view>
                    </view>


                </view>

            </view>


        </view>
        <!-- 加料区 -->
        <view class="optionalBox" v-if="goodsItem.accessories.length > 0">
            <view class="optionalItem">
                <view class="goodsName">加料</view>
                <view class="goodsItem">
                    <view class="optional" :class="{
                        activeOptional: goods.checked,
                    }" @click="handleOptionalAddClick(goods)" v-for="(goods, index) in goodsItem.accessories"
                        :key="goods.id">
                        <view class="name">
                            {{ goods.name }} <text v-if="goods.price != 0 && goods.price">|</text> <text
                                class="goods-price" v-if="goods.price != 0 && goods.price">￥{{ goods.price }}</text>
                        </view>

                        <!-- 售罄蒙版 -->
                        <view class="mode" v-if="goods.enable === false">
                            <view class="mode-text">售罄</view>
                        </view>
                    </view>


                </view>

            </view>


        </view>
        <!-- 提示信息 -->
        <view class="mes">
            1．划线价格：商品展示的划横线的价格是参考价格，并非商品原价而是指不参加优惠的情况下，单品门店价格的总和（单品价总和）。当套餐内容可由您选择组合时，以套餐内可选商品的最低单价总和为为划线价，该价格仅供您参考。
            说明：
            2．非划线价格指参与优惠、使用抵扣券或代金券、在活动时间或满足活动条件、按照套餐组合购买的前提下可能支付的价格，具体的成交价格可能因参加其他活动等而发生变化，最终成交价格以订单结算页价格为准。
            3．产品及包装请以实物为准，图片仅供参考
        </view>
    </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, toRaw, toRefs, watch, nextTick } from 'vue'
import itemImg from '@/static/xfl/item.png'

//props
const props = defineProps({
    product: {
        type: Object,
        default: () => ({})
    },
    productChoose: {  //商品是否可选规则
        type: Boolean,
        default: false
    }
})

const emit = defineEmits(['chooseOptional'])
const chooseOptional = ref() //选中的小料数组种类
const otherStr = ref('')  //选中小料code 
const otherCheckStr = ref({})  //选中小料对象 
const goodsItem = ref()
const hiddenIds = ref<any>([])
const initialGoodsItem = ref()

/**
 * 选中状态变化时触发  
 * item：选中的小料对象
 */

const handleOptionalClick = (groupName: any, item: any, enable?: any) => {

    if (isDisabled(groupName, item)) return uni.showToast({
        title: '该小料不可选',
        icon: 'none'
    })
    // 更新禁用选项
    // updateDisabledOptions();
    // // 清除当前规格下的其他选项的选中状态
    // item.values.forEach(value => {
    //     value.checked = 0;
    // });

    // // 设置当前选项为选中状态
    // goods.checked = 1;

    goodsItem.value.spu_specs.forEach((group: any) => {
        if (group.name === groupName.name) {
            group.values.forEach((ingredient: any) => {
                if (ingredient.name === item.name) {
                    ingredient.checked = !ingredient.checked
                    ingredient.checked = ingredient.checked ? 1 : 0
                } else {
                    ingredient.checked = 0
                }

            })
        }
    })


    // 触发计算并通知父组件
    const selectedIngredients = getSelectedIngredients()
    const goodsNameList = selectedIngredients.map(item => item.name)
    const matchedSku = findMatchingSku(goodsNameList)
    console.log('matchedSku', matchedSku);

    const otherStr = {
        spu_specs: selectedIngredients,
        skuCode: matchedSku.code,
        accessoriesCode: [],
        // price: matchedSku.price,
    }
    goodsItem.value.otherStr = otherStr
    goodsItem.value.otherCheckStr = '/' + selectedIngredients.map(item => {
        let str = ''
        if (Number(item.price) != 0) {
            str = item.name + `￥${item.price}`
        } else {
            str = item.name
        }
        return str
    }).join('/')
    // console.log('初始化默认选中项', goodsItem.value);

    emit('chooseOptional', goodsItem.value)
}
// 加料选中
const handleOptionalAddClick = (item: any) => {
    goodsItem.value.accessories.forEach((group: any) => {
        if (group.name === item.name) {
            group.checked = !group.checked
            group.checked = group.checked ? 1 : 0
        }
    })
    if (goodsItem.value.otherStr && item.checked == 1) {
        goodsItem.value.otherStr.accessoriesCode.push(item.code)
        goodsItem.value.otherStr.price += item.price
    } else if (goodsItem.value.otherStr && item.checked == 0) {
        //删除item.code相同的
        goodsItem.value.otherStr.accessoriesCode = goodsItem.value.otherStr.accessoriesCode.filter((e: any) => e != item.code)
        goodsItem.value.otherStr.price -= item.price
    }
    emit('chooseOptional', goodsItem.value)
}



// 用于存储禁用的小料
const disabledOptions = ref({});

// 检查是否禁用
// 判断是否禁用
const isDisabled = (groupName: any, item: any) => {
    return  hiddenIds.value.includes(item.name);
};


// 更新禁用选项
const updateDisabledOptions = () => {
    const selectedSpecs = goodsItem.value.spu_specs.flatMap(spec =>
        spec.values.filter(value => value.checked === 1).map(v => ({ name: spec.name, spec_name: v.name }))
    );
    console.log(selectedSpecs, '11');


    // 清空之前的禁用选项
    disabledOptions.value = {};

    // 遍历所有规格类型
    goodsItem.value.spu_specs.forEach(spec => {
        const type = spec.name;
        const validOptions = new Set();

        // 遍历所有 SKU，找出有效的组合
        goodsItem.value.sku_infos.forEach(sku => {
            const skuSpecs = sku.specs;
            const isMatch = selectedSpecs.every(selected =>
                skuSpecs.some(s => s.name === selected.name && s.spec_name === selected.spec_name)
            );

            if (isMatch) {
                skuSpecs.forEach(s => {
                    if (s.name === type) {
                        validOptions.add(s.spec_name);
                    }
                });
            }
        });

        // 设置禁用选项
        const allOptions = spec.values.map(v => v.name);
        const disabledList = allOptions.filter(option => !validOptions.has(option));
        disabledOptions.value[type] = disabledList;
    });
};


// 获取所有被选中的小料名称
const getSelectedIngredients = (): { price: string; name: string; skuId: string }[] => {
    const selectedNames: { price: string; name: string; skuId: string }[] = []
    if (!goodsItem.value.spu_specs) return selectedNames
    goodsItem.value.spu_specs.forEach((group: any) => {

        group.values.forEach((ingredient: any) => {
            if (ingredient.checked) {
                selectedNames.push({ name: ingredient.name, price: ingredient.price, skuId: ingredient.code })
            }
        })
    })
    // console.log('选中的小料名称', selectedNames);

    return selectedNames
}

// 根据选中小料匹配对应的 sku
const findMatchingSku = (selectedIngredients: string[]) => {
    const { sku_infos: skus } = goodsItem.value
    if (!Array.isArray(skus)) return null
    return skus.find((sku: any) => {
        if (!Array.isArray(sku.specs)) return false
        const specNames = sku.specs.map((v: any) => v.spec_name)
        return (
            selectedIngredients.length === specNames.length &&
            selectedIngredients.every(name => specNames.includes(name))
        )
    })
}

// 初始化默认选中项
const allList = ref([]) //全部类型小料
const initDefaultSelection = () => {
    // 获取全部小料的名称
    allList.value = goodsItem.value.spu_specs.flatMap(group => group.values.map(item => item.name))
    const selectedIngredients = getSelectedIngredients()
    console.log(selectedIngredients,'价格');
    
    const goodsNameList = selectedIngredients.map(item => item.name)
    const matchedSku = findMatchingSku(goodsNameList)

    const otherStr = {
        spu_specs: selectedIngredients,
        skuCode: matchedSku.code,
        accessoriesCode: [],
    }
    console.log(otherStr,'otherStr');
    
    goodsItem.value.otherStr = otherStr
    goodsItem.value.otherCheckStr = '/' + selectedIngredients.map(item => {
        let str = ''
        if (Number(item.price) != 0) {
            str = item.name + `￥${item.price}`
        } else {
            str = item.name
        }
        return str
    }).join('/')
    // console.log('初始化默认选中项', goodsItem.value);
    emit('chooseOptional', goodsItem.value)
}


// 初始化隐藏的小料
const initializeHiddenIds = () => {
    hiddenIds.value = [];
    goodsItem.value.spu_specs?.forEach((item: any) => {
        item.values.forEach((goods: any) => {
            if (goods.checked === 1) {
                //获取到匹配的元素
                const matchedEl = goodsItem.value.sku_infos.filter(el => {
                    return el.specs.some(o => o.spec_name === goods.name);
                });
                // console.log('匹配的 el:', goods.name, matchedEl);

                // skuInfoNameList 是 选中的小料==》全部符合sku_infos匹配的name总和数组
                let skuInfoNameList = [...new Set(matchedEl.flatMap(el => el.specs.map(o => {
                    return o.spec_name
                }).filter(item => item !== goods.name)))]
                // console.log(skuInfoNameList, 'options的str')
                // typeList是 在选中的类型下面全部小料数组
                let typeList = goodsItem.value.spu_specs.filter(el => {
                    return el.name == item.name
                })
                // console.log(typeList, '选中的',allList.value);
                // typeNameList 是 选中的类型下面全部小料的name数组
                let typeNameList = typeList.flatMap(group => group.values.map(item => item.name))
                // console.log(typeNameList, '选中的str');

                //allList.value是全部小料： list1是从全部小料中排除先排除选中的类型中小料的name，list2是再排除sku_infos匹配符合的name，剩余就是未选中的小料
                let list1 = allList.value.filter(item => !typeNameList.includes(item))
                //list2就是未选中的数组
                let list2 = list1.filter(item => !skuInfoNameList.includes(item))
                hiddenIds.value = [...new Set([...hiddenIds.value, ...list2])];
            }
        });
    });
};


// 监听 product 变化，重新初始化
watch(
    () => props.product,
    (newVal) => {
        if (newVal) {
            goodsItem.value = JSON.parse(JSON.stringify(newVal))

            initDefaultSelection()
        }
    },
    { immediate: true, deep: true }
)


// 监听 checked 属性的变化
watch(
    () => goodsItem.value.spu_specs,
    (newspu_specs) => {
        
        hiddenIds.value = [];
        newspu_specs.forEach((item: any) => {
            item.values.forEach((goods: any) => {
                if (goods.checked === 1) {
                    //获取到匹配的元素
                    const matchedEl = goodsItem.value.sku_infos.filter(el => {
                        return el.specs.some(o => o.spec_name === goods.name);
                    });
                    // console.log('匹配的 el:', goods.name, matchedEl);

                    // skuInfoNameList 是 选中的小料==》全部符合sku_infos匹配的name总和数组
                    let skuInfoNameList = [...new Set(matchedEl.flatMap(el => el.specs.map(o => {
                        return o.spec_name
                    }).filter(item => item !== goods.name)))]
                    // console.log(skuInfoNameList, 'options的str')
                    // typeList是 在选中的类型下面全部小料数组
                    let typeList = goodsItem.value.spu_specs.filter(el => {
                        return el.name == item.name
                    })
                    // console.log(typeList, '选中的',allList.value);
                    // typeNameList 是 选中的类型下面全部小料的name数组
                    let typeNameList = typeList.flatMap(group => group.values.map(item => item.name))
                    // console.log(typeNameList, '选中的str');

                    //allList.value是全部小料： list1是从全部小料中排除先排除选中的类型中小料的name，list2是再排除sku_infos匹配符合的name，剩余就是未选中的小料
                    let list1 = allList.value.filter(item => !typeNameList.includes(item))
                    //list2就是未选中的数组
                    let list2 = list1.filter(item => !skuInfoNameList.includes(item))

                    hiddenIds.value = [...new Set([...hiddenIds.value, ...list2])];
                }
            });
        });
    },
    { deep: true }
);


// 页面加载时初始化隐藏的小料
onMounted(() => {
    initializeHiddenIds();
});
</script>

<style lang="scss" scoped>
.goodsChoose {
    // height: calc(100vh - 400rpx);
    // margin-bottom: 1300rpx;
    background-color: #fff;

}

.goodsSize1 {

    .goodsItem {
        display: flex;
        flex-wrap: wrap;


        .required {
            width: 150rpx;
            height: 160rpx;
            border-radius: 10rpx;
            text-align: center;
            margin: 30rpx;
            // margin-bottom: 50rpx;
            border: 2rpx solid #f1f1f1;

            // .img{
            //     height: 160rpx;

            // }
            .name {
                font-size: 24rpx;
            }
        }
    }


    .goodsSize1_1 {
        font-weight: 700;
        margin: 40rpx 0;
    }

    .goodsSize1_2 {
        margin-bottom: 40rpx;
    }

}

.optionalBox {
    .optionalItem {
        .goodsItem {
            display: flex;
            flex-wrap: wrap;

            .optional {
                position: relative;


                // height: 60rpx;
                // line-height: 60rpx;
                border: 2rpx solid #f1f1f1;
                border-radius: 10rpx;
                text-align: center;
                margin: 30rpx;
                // margin-bottom: 80rpx;
                background-color: #f6f5f8;
                // color: #949496;

                .mode {
                    position: absolute;
                    top: 0;
                    width: 100%;
                    height: 100%;
                    background-color: rgba(25, 14, 14, 0.4);

                    .mode-text {
                        color: #e9e9e9;
                    }
                }

                .name {
                    min-width: 150rpx;
                    padding: 10rpx;
                    font-size: 24rpx;
                }
            }
        }

    }
}

.goodsName {
    font-size: 28rpx;
    // color: #969696;
    color: #333;
    font-weight: 700;
    margin: 20rpx 0;


}

.mes {
    height: 500rpx;
    font-size: 20rpx;
    color: #969696;
    margin-top: 50rpx;
}

//选中了小料
.activeOptional {
    color: #ea7721 !important;
    border: 2rpx solid #ff6c18 !important;
    background-color: #fef1ec !important;
    /* 蓝色半透明蒙版 */
    //   opacity: 0.8; /* 可选：整体透明度控制 */
}


.hidden {
    display: none;

}

.hiddenBorder {
    margin: 0 !important;
    border: none !important;

}

.disabled {
    color: #949496 !important;
}
</style>
